<!--
 * @description  : 证件-预警核查处理
 * @descriptionDetail: 证件-预警核查处理
 * @copyright    : 浙江烟草
 * @author       : dw
 * @create       : 2022-11-15 15:29:13
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="navTitle" :custom-back="goBack" style="z-index: 99999">
    </theme-navbar>
    <!-- #endif -->
    <view :class="[isDisabled ? 'content-btn':'content']">
      <view>
        <view class="CT-title">
          停止经营六个月预警核查
        </view>
        <u-row class="pd-tp">
          <u-col span="6" class="pd-lf">
            <view class="CT-label">
              预警日期：
            </view>
            <view class="CT-value">
              {{ detailInfo.warningStartDate || '/' }}
            </view>
          </u-col>
          <u-col span="6" class="pd-lf">
            <view class="CT-label">
              最后一次进货日期
            </view>
            <view class="CT-value">
              {{ detailInfo.finallyOrderGoods || '/' }}
            </view>
          </u-col>
        </u-row>
        <u-row class="pd-tp">
          <u-col span="6" class="pd-lf">
            <view class="CT-label">
              停业到期结束日期
            </view>
            <view class="CT-value">
              {{ detailInfo.closeDownEndDate || '/' }}
            </view>
          </u-col>
        </u-row>
      </view>
      <view v-if="isShowNotice">
        <view style="border-bottom: 20rpx solid #f2f3f5;margin: 26rpx -56rpx;"></view>
        <view class="form-style">
          <view class="form-style-title">
            <view class="left-info-tag"></view>
            <view class="fs-title">
              收回许可证事先告知书
            </view>
          </view>
          <u-row v-if="haveDoc">
            <u-col span="11" class="CT-label" style="color: #2979ff;" @tap="downloadFile(pdfFileId)">
              {{ fullDocNo }}
            </u-col>
            <u-col span="1">
              <u-icon v-if="isSigneds" name="share" :color="$theme.u_type_success" size="28" @tap="downloadFile(pdfFileId)"></u-icon>
              <u-icon v-else name="share" :color="$theme.u_type_primary" size="28" @tap="handleSigns"></u-icon>
            </u-col>
          </u-row>
          <u-form v-if="haveDoc==false" :model="docInfo" ref="docForm" label-width="140" label-position="top" :border-bottom="false" :label-style="labelStyle">
            <u-row>
              <u-col span="12" style="padding: 0px 0px">
                <u-form-item label="公告时间">
                  <z-date placeholder="请选择公告时间" v-model="docInfo.publishDate" />
                </u-form-item>
              </u-col>
              <u-col span="12" style="padding: 0px 0px">
                <u-form-item label="承办人（请选择两位）">
                  <u-input placeholder="请选择承办人" v-model="docInfo.transName" @click="orgPersonSelectShow = true"></u-input>
                </u-form-item>
              </u-col>
              <u-col span="12">
                <u-button align="right" style="width:100%" type="primary" v-if="haveDoc==false" :plain="true" size="medium" @tap="handleDoc">
                  点击生成事先告知书
                </u-button>
              </u-col>
            </u-row>
          </u-form>
        </view>
      </view>
      <u-popup mode="bottom" height="80%" v-model="orgPersonSelectShow">
        <org-person-select treeType="zm-user" @choose="handlerChoosePerson"></org-person-select>
      </u-popup>
      <view style="border-bottom: 20rpx solid #f2f3f5;margin: 26rpx -56rpx;"></view>
      <view class="form-style">
        <view class="form-style-title">
          <view class="left-info-tag"></view>
          <view class="fs-title">
            基本信息
          </view>
        </view>
        <u-form :model="baseInfo" label-width="140" label-position="top" :border-bottom="false" :label-style="labelStyle">
          <u-row>
            <u-col span="12" style="padding: 0px 0px">
              <u-form-item label="许可证号">
                {{ detailInfo.licNo || '/' }}
              </u-form-item>
            </u-col>
          </u-row>
          <u-row>
            <u-col span="12" style="padding: 0px 0px">
              <u-form-item label="经营者/法定代表人">
                {{ detailInfo.managerName || '/' }}
              </u-form-item>
            </u-col>
          </u-row>
          <u-row>
            <u-col span="12" style="padding: 0px 0px">
              <u-form-item label="企业(字号)名称">
                {{ detailInfo.companyName || '/' }}
              </u-form-item>
            </u-col>
          </u-row>
          <u-row>
            <u-col span="12" style="padding: 0px 0px">
              <u-form-item label="许可证状态">
                {{ detailInfo.licStatusName || '/' }}
              </u-form-item>
            </u-col>
          </u-row>
          <u-row>
            <u-col span="12" style="padding: 0px 0px">
              <u-form-item label="经营地址">
                {{ detailInfo.businessAddr || '/' }}
              </u-form-item>
            </u-col>
          </u-row>
        </u-form>
      </view>
      <view style="border-bottom: 20rpx solid #f2f3f5;margin: 26rpx -56rpx;"></view>
      <view class="form-style">
        <view class="form-style-title">
          <view class="left-info-check-tag"></view>
          <view class="fs-title">
            核查信息
          </view>
        </view>
        <u-form :model="checkInfo" ref="uForm" :error-type="['border-bottom','message',]" label-width="140" rules="rules" label-position="top" :border-bottom="false" :label-style="labelStyle">
          <u-row>
            <u-col span="12" style="padding: 0px 0px">
              <u-form-item prop="isClosePlace">
                <view class="loc-box" style="width:100%;padding: 0rpx;">
                  <view class="loc-inline" style="font-size:26rpx;">
                    <span style="color:#fa3534;margin-left: -12rpx;padding-right: 4rpx"></span>经营场所是否关闭
                  </view>
                  <view class="inline-box">
                    <z-dict-radio :dictType="$u.dic.DIC_KEYS.S_SYS_YES_NO" :disabled="isDisabled" v-model="isClosePlace" @input="closePlace"></z-dict-radio>
                  </view>
                </view>
              </u-form-item>
            </u-col>
          </u-row>
          <u-row>
            <u-col span="12" style="padding: 0px 0px">
              <u-form-item prop="isStopBusiness">
                <view class="loc-box" style="width:100%;padding: 0px;">
                  <view class="loc-inline" style="font-size:26rpx;">
                    <span style="color:#fa3534;margin-left: -12rpx;padding-right: 4rpx">*</span>烟草专卖零售许可证持证人停止向当地烟草专卖批发企业订货并停止烟草制品零售业务
                  </view>
                  <view class="inline-box">
                    <z-dict-radio :dictType="$u.dic.DIC_KEYS.S_SYS_YES_NO" :disabled="isDisabled" v-model="isStopBusiness" @input="stopBusiness"></z-dict-radio>
                  </view>
                </view>
              </u-form-item>
            </u-col>
          </u-row>
          <u-row>
            <u-col span="12" style="padding: 0px 0px">
              <u-form-item label="备注">
                <u-input type="textarea" :disabled="isDisabled" v-model="checkInfo.remark"></u-input>
              </u-form-item>
            </u-col>
          </u-row>
          <u-row>
            <u-col span="12" style="padding: 0px 0px">
              <u-form-item label="收回核查日期">
                {{ endDate || '/' }}
              </u-form-item>
            </u-col>
          </u-row>
          <u-row>
            <u-col span="12" style="padding: 0px 0px">
              <u-form-item label="收回核查人">
                {{ creatorName }}
              </u-form-item>
            </u-col>
          </u-row>
          <u-row>
            <u-col span="12" style="padding: 0px 0px">
              <u-form-item label="图片上传" :required="true">
                <m-upload
                  maxCount="5"
                  :uploadParam="fileUploadParam"
                  upApiUrl="uploadBase64ForApp"
                  :file-list="fileList"
                  :disabled="isDisabled"
                  :deletable="!isDisabled"
                  @on-list-change="changeUpload"
                  class="upload-sty"
                ></m-upload>
                <u-image
                  width="100%"
                  v-if="fileList.length == 0 && isDisabled"
                  height="330rpx"
                  style="padding:0 0 34rpx 14rpx"
                  mode="scaleToFill"
                  :src="'/static/certificate/noImg.png'"
                >
                </u-image>
              </u-form-item>
            </u-col>
          </u-row>
        </u-form>
      </view>
    </view>
    <view class="submit-btns btn-other-cls">
      <u-button type="primary" v-if="!isDisabled" @click="save">
        提交
      </u-button>
    </view>
    <u-calendar max-date="2099-12-31" v-model="receiveDateRange" @change="handlerReceiveDate"></u-calendar>
    <u-popup v-model="qrcodeShow" mode="bottom" height="70%" @close="qrcodeShow=false">
      <view class="qrcodeContainer">
        <img :src="qrcodeImg" alt="暂无图片" />
        <p>请扫码签名</p>
      </view>
    </u-popup>
  </view>
</template>

<script>
import MUpload from "@/components/m-upload.vue";
import { uuid, } from '@/common/util.js';
import { ZDictRadio,ZDate, } from '@/components';
import certificateService from "@/service/certificate/certificate.service.js";
import commonService from '@/service/common/common.service';
import { L_WARN_TYPE, } from "@/service/case/mapping/enum.js";
import OrgPersonSelect from "@/components/org-person-select.vue";
import QRCode from 'qrcode';
export default {
  components: {
    MUpload,
    ZDictRadio,
    OrgPersonSelect,
    ZDate,
  },
  data() {
    return {
      rules:{
        isStopBusiness:[{
          required:true,
          message:'请选择',
          trigger: ['change', 'blur',],
        },],
      },
      customStyle:{
        padding:"20rpx 32rpx",
      },
      labelStyle:{
        'color':"#666666",
        'font-size':'13px',
      },
      remarks: '',
      fileUploadParam:{
        fiGroupCode:this.$FILE_GROUP_TYPE.l_supplement_img,
        bizId:"",
      },
      baseInfo: {}, // 基本信息
      checkInfo: {
      }, // 审核信息
      fileList: [],
      receiveDateRange: false,
      detailInfo: {},
      endDate: '',
      user: this.$store.state.userInfo,
      isDisabled: false,
      isClosePlace: "",
      isStopBusiness: "",
      isShowNotice: false,  // 是否显示收回许可证事先告知书，根据配置决定是否开启
      orgPersonSelectShow: false,
      docInfo: {},// 告知信息
      haveDoc: false,
      fullDocNo: '',
      pdfFileId: '',
      docInsUuid: '',
      managerName: '',
      managerIdCardNo: '',
      qrcodeShow: false,
      qrcodeImg: null,
      signViewUrl: null,
      isSigneds:false,
    }
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  onLoad() {
    this.objInfo = this.getRouteParam();
    this.fileUploadParam.bizId = this.objInfo.bizUuid;
    this.endDate = this.$u.timeFormat(new Date().getTime(), 'yyyy年mm月dd日');
    this.creatorName = this.user.user.personName;
  },
  created () {
    this.initAuditImage();
    this.init();
  },
  mounted () {
    // this.init();
  },
  methods: {
    init () {
      let params = {
        id: this.objInfo.bizUuid,
      }
      this.$modal.showLoading('加载中...');
      certificateService.recoverWarnCheck(params).then(res => {
        if (res.success) {
          this.$modal.hideLoading();
          this.detailInfo = res.bean;
          this.searchKind();
          if (res.bean.isClosePlace === undefined) {
            this.isClosePlace = ''
          } else {
            this.isClosePlace = res.bean.isClosePlace == true ? '1' : '0';
          }
          if (res.bean.isStopBusiness === undefined) {
            this.isStopBusiness = ''
          } else {
            this.isStopBusiness = res.bean.isStopBusiness == true ? '1' : '0';
          }
          // this.checkInfo.isClosePlace = res.bean.isClosePlace == true ? '1' : '0';
          // this.checkInfo.isStopBusiness = res.bean.isStopBusiness == true ? '1' : '0';
          this.checkInfo.remark = res.bean.remark;
          if (res.bean.recoverDate) {
            this.endDate = res.bean.recoverDate;
          }
          if (this.$u.test.isEmpty(res.bean.taskUuid)) {
            this.isDisabled = false
          } else {
            this.isDisabled = true
          }
        } else {
          this.$modal.hideLoading();
          console.log(res)
        }
      }).catch(err => {
        this.$modal.hideLoading();
        console.log(err)
      })
    },
    closePlace (e) {
      this.isClosePlace = e
      this.checkInfo.isClosePlace = e
      console.log(this.isClosePlace)
    },
    stopBusiness (e) {
      this.isStopBusiness = e
      this.checkInfo.isStopBusiness = e
    },
    initAuditImage(){
      certificateService.goFiles(this.objInfo.bizUuid,this.$FILE_GROUP_TYPE.l_supplement_img).then(res => {
        if (res.success) this.fileList = res.data;
      }).catch(e => {
        console.log(e);
      })
    },
    handlerReceiveDate(e){
      this.checkInfo.backTime = e.result;
    },
    // 上传/删除图片事件
    changeUpload(list, key){
      if(list.length > 0){
        this.fileList = [...list,];
      }else{
        this.fileList = [];
      }
    },
    save () {
      console.log(this.checkInfo);
      this.$refs.uForm.validate(valid => {
        if (valid) {
          if (this.isClosePlace == '0') {
            this.isClosePlace = false
          } else if (this.isClosePlace == '1') {
            this.isClosePlace = true
          } else {
            this.isClosePlace = ''
          }
          // this.isClosePlace = this.isClosePlace == '0' ? false : true;
          this.isStopBusiness = this.isStopBusiness == '0' ? false : true;
          let pars = {
            isClosePlace: this.isClosePlace,
            isStopBusiness: this.isStopBusiness,
            creatorName: this.creatorName,
            recoverDate: this.endDate,
            remark: this.checkInfo.remark,
            file: '',
            warnCheckUuid: '',
            closeDownEndDate:'',
          }
          if (this.isShowNotice && !this.haveDoc) {
            this.$modal.confirm('当前未生成收回许可证事先告知书，是否确认提交?', () => {
              let tips = "";
              if (this.fileList.length == 0) return this.$u.toast("请添加图片");
              if (this.isStopBusiness) {
                tips = "核查满足公告条件，是否提交并自动发布公告？";
              } else {
                tips = "核查不满足公告条件，是否忽略该预警并提交？忽略后该任务3个月后会自动启动。";
              }
              this.$modal.alert(tips, '提示', () => {
                let params = { ...this.detailInfo, ...pars, };
                this.$modal.showLoading('提交中...');
                certificateService.saveOrUpdate(params).then(res => {
                  if (res.success) {
                    this.$modal.hideLoading();
                    this.backPrev({
                      paramKey: 'refresh',
                      param: true,
                    })
                  }
                }).catch(err => {
                  this.$modal.hideLoading();
                  console.log(err);
                  this.$u.toast(err.msg);
                });
              }, '', true);
            }).catch(err => {
              return false
            });
          } else {
            let tips = "";
            if (this.fileList.length == 0) return this.$u.toast("请添加图片");
            if (this.isStopBusiness) {
              tips = "核查满足公告条件，是否提交并自动发布公告？";
            } else {
              tips = "核查不满足公告条件，是否忽略该预警并提交？忽略后该任务3个月后会自动启动。";
            }
            this.$modal.alert(tips, '提示', () => {
              let params = { ...this.detailInfo, ...pars, };
              this.$modal.showLoading('提交中...');
              certificateService.saveOrUpdate(params).then(res => {
                if(res.success){
                  this.$modal.hideLoading();
                  this.backPrev({
                    paramKey:'refresh',
                    param:true,
                  })
                }
              }).catch(err => {
                this.$modal.hideLoading();
                console.log(err);
                this.$u.toast(err.msg);
              });
            }, '',true);
          }
        } else {
          console.log('验证失败');
        }
      });
    },
    // 判断是否为浙江特例
    searchKind () {
      commonService.getSysConfig('RLIC_SYS', 'recoverNoticeSwitch').then(d => {
        if (d.success &&  d.msg == "1") {
          this.isShowNotice = true
          // 查询第三方签名地址
          commonService.getThirdSign().then(ud => {
            if (ud.success) {
              this.signViewUrl = ud.data?.filter(d => d.configSubKey === 'viewUrl')[0]?.configValue;
            }
          });
          // 如果是判断有没有生成告知书
          certificateService.getRecoverAdvanceNotice({followupMonitorWarnId:this.detailInfo.followupMonitorWarnId,}).then(dr => {
            if (dr.bean) {
              this.haveDoc = true;
              this.pdfFileId = dr.bean.pdfFileId
              this.fullDocNo = dr.bean.fullDocNo
              this.docInsUuid = dr.bean.docInsUuid
              // 查询是否已完成第三方签名
              commonService.isSigned(this.docInsUuid).then(s => {
                if (!s.success) {
                  this.isSigneds = true
                } else {
                  this.isSigneds = false
                }
              });
            } else {
              this.haveDoc = false;
            }
          })
        }
      })
    },
    // 生成文书
    handleDoc () {
      if (!this.docInfo.transName){
        this.$u.toast('请选择承办人！');
        return false
      }
      if (!this.docInfo.publishDate){
        this.$u.toast('请选择公告时间！');
        return false
      }
      let paras = {
        'licNo': this.detailInfo.licNo,
        'businessAddr': this.detailInfo.businessAddr,
        'warnType': L_WARN_TYPE.STOP_SIX_MONTH,
        'followupMonitorWarnId':this.detailInfo.followupMonitorWarnId,
        'transName': this.docInfo.transName,
        'transId': this.docInfo.transId,
        'publishDate':this.docInfo.publishDate,
      }
      certificateService.AdvanceNotice(paras).then(d => {
        if (d.success == true) {
          // 提交成功后查一遍文书详情拿到参数
          certificateService.getRecoverAdvanceNotice({ followupMonitorWarnId: this.detailInfo.followupMonitorWarnId, }).then(d => {
            if (d.success) {
              this.haveDoc = true;
              this.pdfFileId = d.bean.pdfFileId
              this.fullDocNo = d.bean.fullDocNo
              this.docInsUuid = d.bean.docInsUuid
            }
          })
        } else {
          this.haveDoc = false;
          this.$u.toast(d.msg)
        }
      })
    },
    // 文书预览
    downloadFile(pdfFileId){
      if (!pdfFileId) {
        this.$u.toast("没有文书");
        return;
      }
      this.setRouteParam({fileId:pdfFileId,});
      this.$u.route('pages/commonPage/printerComponent');
    },
    // 选择承办人
    handlerChoosePerson (psrList) {
      if (psrList.length != 2) {
        this.$u.error('请选择两位承办人！')
        return false;
      }
      let names = [];
      let ids = [];
      psrList.forEach(p => {
        names.push(p.name);
        ids.push(p.id);
      });
      certificateService.getCertNoById(ids).then(d => {
        if (d.success) {
          this.docInfo.transName = d.bean.join(",");
          this.docInfo.transId = ids.join(",");
        }
      })
      this.orgPersonSelectShow = false;
    },
    // 第三方签名
    handleSign(signDocInsUuid) {
      this.$u.loading("检查签名中...");
      commonService.isSigned(signDocInsUuid).then(s => {
        this.$u.hideLoading();
        if (!s.success) {
          // 再次查询时重置一下结果，改变图标显示
          this.isSigneds = true
          this.$u.toast(s.msg);
          return;
        }
        if (!this.managerName || !this.managerIdCardNo) {
          this.$u.hideLoading();
          this.$u.error(!this.managerName ? "缺少被核查人姓名" : "缺少被核查人身份证号");
          return;
        }
        // 检查当事人数据是否正确，再调用接口
        commonService.dsrSign(signDocInsUuid, this.managerName, this.managerIdCardNo).then(dr => {
          this.$u.hideLoading();
          if (!dr.success) {
            this.$u.error(dr.msg);
            return;
          }
          let qrcodeUrl = `${this.signViewUrl}?token=${dr.bean}`;
          this.$modal.confirm("是否生成二维码给被核查人扫码签名？", () => {
            QRCode.toDataURL(qrcodeUrl).then(path => {
              this.qrcodeImg = path;
              this.qrcodeShow = true;
            }).catch(err => {
              this.$u.error(err);
            });
          }, () => {
            this.$modal.openNewTab(qrcodeUrl);
          }, "生成二维码", "本机签名");
        });
      });
    },
    handleSigns () {
      // 获取签名需要的身份证号
      certificateService.getRetailcerCertificate({ retailerUuid: this.detailInfo.retailerUuid, },).then(d => {
        if (d.success) {
          this.managerIdCardNo = d.bean.licenseInfoPre.managerCredNum;
          this.managerName = d.bean.licenseInfoPre.managerName;
          this.handleSign(this.docInsUuid);
        }
      })
    },
  },
}
</script>

<style scoped lang="scss">
@import "style/certificate/common.scss";
.page{
  padding: 0;
}
.upload-sty{
  margin-left: -12rpx;
}
.pd-lf{
  padding-left: 0;
}
.pd-tp{
  padding-top: 13px;
}
.content{
  padding: 24rpx 36rpx 180rpx 36rpx;
}
.content-btn{
  padding: 24rpx 36rpx 20rpx 36rpx;
}
.CT-title{
  font-size: 18px;
  font-weight: bold;
  padding-bottom: 18px;
  border-bottom: 1px solid #DADADD;
}
.CT-label{
  font-size: 13px;
  color: #989EA1;
  padding-bottom: 6px;
}
.CT-value{
  font-size: 14px;
  color: #393B3D;
}
.form-style-title{
  display: flex;
  justify-content: flex-start;
  flex-direction: row;
  width: 100%;
  align-items: flex-start;
}
.form-style{
  padding: 0rpx 8rpx
}
.left-info-tag{
  padding: 8px 2px;
  background-color: #0079F2 ;
  border-radius: 22px;
  margin: 3px 6px 13px 0px;
}
.left-info-check-tag{
  padding: 8px 2px;
  background-color: #ee8c4f;
  border-radius: 22px;
  margin: 3px 6px 13px 0px;
}
.fs-title{
  font-weight: bold;
  font-size: 32rpx;
}
.loc-box {
  line-height: 38px;
  padding: 11px 0;
  font-size: 13px;
  color: #303133;
}
.inline-box {
  display: flex;
  align-items: center;
}
.loc-inline{
  font-size: 13px;
  color: #666666;
}
.qrcodeContainer {
  text-align: center;
  img {
    width: 95%;
  }
  p {
    font-size: 18px;
    font-weight: 600;
    color: #333;
  }
}
</style>
